/*
 * 文件名： CheckOrderWechatWcPayCiticImpl.java
 * 
 * 工程名称: checkorder-service
 *
 * Gopay
 *
 * 创建日期： 2016年10月12日
 *
 * Copyright(C) 2016, by www.gopay.com.cn Inc.All rights reserved.
 *
 * 原始作者: 宣广海
 *
 */
package com.gopay.checkorder.service.impl.wcpay;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.task.BankCountDownLatch;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BankOrderStatus;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.bank.WechatScanConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.WcPayBaseMessage;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.bank.wechat.wcpay.citic.res.WcPayQueryResMsg;
import com.gopay.common.domain.bank.wechat.wcpay.citic.res.WcRefundItem;
import com.gopay.common.domain.bank.wechat.wcpay.citic.res.WcRefundQueryResMsg;
import com.gopay.common.domain.cashier.BankCardType;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.domain.cps.vo.InAccInfo;
import com.gopay.remote.bank.WcPayInteractRemoteService;

/**
 * 公众号支付结果对账
 *
 * @author 宣广海
 *
 * @version 
 *
 * @since 2016年10月12日
 */
public class CheckOrderWechatWcPayCiticImpl implements BankOrderService{
	
	/**
	 * 定义日志对象
	 */
	private final static Logger logger = LoggerFactory.getLogger("WECHAT-WCPAY-CITIC");
	@Resource(name = "wcPayClient")
	private WcPayInteractRemoteService wcPayClient;

	@Override
	public CheckOrderResult checkOrder(BankOrder bankOrder, String target) {

		/**
		 * 对单返回对象
		 */
		CheckOrderResult checkOrderResult = new CheckOrderResult();
		checkOrderResult.setSuccess(false);
		checkOrderResult.setOrderId(bankOrder.getOrderId());

		WcPayBaseMessage message = new WcPayBaseMessage();

		message.setOrderId(bankOrder.getOrderId()); // 国付宝系统订单号
		message.setBankOrderId(bankOrder.getOutOrderId());// 上送银行单号
		message.setBank(BankConstants.BANK_LOGO_WECHAT);// 微信
		message.setBankIntrChann(BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()));// 银行通道码
		message.setBankBusProd(BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));// 银行业务产品码
		message.setBank(bankOrder.getBankCode());

		Result result = new Result();
		try {
			if (BisBankBusinessProd._12.value.equals(bankOrder.getBankBizProdCode())) {
				/**
				 * 退款交易请求退款查询接口 add by 宣广海 20161013
				 */
				message.setTkOriBankOrderId(bankOrder.getOriOutOrderId());// 原订单号
				result = wcPayClient.refundQuery(message);
				return refundCheckOrder(result, bankOrder);
			} else {
				result = wcPayClient.orderQuery(message);
			}
			
			if (result == null || !result.isSuccess()) {
				logger.error("wcPayClient fail.");
				if (result == null || ProcCodeConstants.PROC_CODE_100F1002.equals(result.getResultCode())
						|| ProcCodeConstants.PROC_CODE_100E7027.equals(result.getResultCode())) {
					BankCountDownLatch.failIncrease(bankOrder.getBankCode());
				}
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
				checkOrderResult.setErrMsg("系统返回对账结果为空");
				return checkOrderResult;
			}

			WcPayQueryResMsg res = (WcPayQueryResMsg) result.getDefaultModel();
			if (res == null) {
				/**
				 * 查询结果为空
				 */
				logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:"
						+ ProcCodeConstants.PROC_CODE_100E6022 + " err:bis query is null.");
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
				checkOrderResult.setErrMsg("返回对账结果为空");
				return checkOrderResult;
			}
			/**
			 * 状态为0表示通讯成功
			 */
			if ("0".equals(res.getStatus())) {
				/**
				 * result_code为0表示业务成功
				 */
				if ("0".equals(res.getResult_code())) {
					/**
					 * 支付成功
					 */
					if (WechatScanConstants.WECHAT_WCPAY_QUERY_SUCCESS.equals(res.getTrade_state())) {
						
						checkOrderResult.setSuccess(true);
						
						InAccInfo accInfo = new InAccInfo();
						accInfo.setOrderId(bankOrder.getOrderId());				
						accInfo.setAmount(res.getAmount());
						accInfo.setRetCode("00");
						accInfo.setCardType(BankCardType.Unknown.toString());
						checkOrderResult.setAccInfo(accInfo);
						logger.error("微信公众号支付订单：" + bankOrder.getOrderId() + "，交易成功" + "返回码：" + res.getTrade_state());
					} else if (WechatScanConstants.WECHAT_WCPAY_QUERY_NOTPAY.equals(res.getTrade_state())) {
						checkOrderResult.setErrMsg("微信公众号支付订单进行中！");
						logger.error("微信公众号支付订单：" + bankOrder.getOrderId() + "，交易处理中" + "返回码：" + res.getTrade_state());
					} else if (WechatScanConstants.WECHAT_WCPAY_QUERY_REFUND.equals(res.getTrade_state())) {
						checkOrderResult.setErrMsg("微信扫码订单转入退款！");
						logger.error("微信公众号支付订单：" + bankOrder.getOrderId() + "，交易转入退款" + "返回码：" + res.getTrade_state());
					} else if (WechatScanConstants.WECHAT_WCPAY_QUERY_CLOSED.equals(res.getTrade_state())) {
						checkOrderResult.setErrMsg("微信扫码订单已关闭！");
						logger.error("微信公众号支付订单：" + bankOrder.getOrderId() + "，交易已关闭" + "返回码：" + res.getTrade_state());
					}else if (WechatScanConstants.WECHAT_WCPAY_QUERY_REVERSE.equals(res.getTrade_state())) {
						checkOrderResult.setErrMsg("微信扫码订单已冲正！");
						logger.error("微信公众号支付订单：" + bankOrder.getOrderId() + "，交易已冲正" + "返回码：" + res.getTrade_state());
					}else {
						checkOrderResult.setErrMsg("微信公众号支付返回交易状态不明");
						logger.error(
								"微信公众号支付订单：" + bankOrder.getOrderId() + "，返回交易状态不明，系统暂不处理" + "返回码：" + res.getTrade_state());
					}
				}else{
					checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
					checkOrderResult.setErrMsg("系统返回对账结果为空");
					logger.error("支付订单：" + bankOrder.getOrderId() + "，查询失败" + "err_code：" + res.getErr_code() + "。错误信息为："
							+ res.getErr_msg());
				}
			} else {
				checkOrderResult.setErrMsg("微信返回验签失败");
				logger.error("微信公众号支付订单：" + bankOrder.getOrderId() + "，验签失败" + "status：" + res.getStatus() + "。返回信息为："
						+ res.getMessage());
			}
			return checkOrderResult;
		} catch (Exception e) {
			logger.error("wcPayClient fail.", e);
			checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
			checkOrderResult.setErrMsg("微信公众号支付对账异常");
			return checkOrderResult;
		}

	
	}

	/**
	 * 
	 * 功能描述：退款订单对账
	 *
	 * @param result
	 * @param bankOrder
	 * @return
	 * 
	 * @author 宣广海
	 *
	 * @since 2016年10月14日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public CheckOrderResult refundCheckOrder(Result result, BankOrder bankOrder) {

		CheckOrderResult checkOrderResult = new CheckOrderResult();
		checkOrderResult.setSuccess(false);
		if (result == null || !result.isSuccess()) {
			logger.error("refund bankClient fail.");
			if (result == null || ProcCodeConstants.PROC_CODE_100E6062.equals(result.getResultCode())) {
				BankCountDownLatch.failIncrease(bankOrder.getBankCode());
				checkOrderResult.setCommunicateError(true);
			}
			checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6062);
			checkOrderResult.setErrMsg("系统返回对账结果为空");
			return checkOrderResult;
		}
		WcRefundQueryResMsg res = (WcRefundQueryResMsg) result.getDefaultModel();
		if (res == null) {
			// 查询订单为空
			logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:" + ProcCodeConstants.PROC_CODE_100E5062
					+ " err:bis query is null.");
			checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
			checkOrderResult.setErrMsg("银行返回对账结果为空");
			return checkOrderResult;
		}
		/**
		 * 状态为0表示通讯成功
		 */
		if ("0".equals(res.getStatus())) {
			/**
			 * result_code为0表示业务成功
			 */
			if ("0".equals(res.getResult_code())) {
				/**
				 * 支付成功,威富通会返回多笔退款交易
				 */
				int refundCount = res.getRefund_count();
				for (int i = 0; i < refundCount; i++) {
					WcRefundItem refundItem = res.getRefundItems().get(i);
					logger.error("威富通返回退款订单号为："+refundItem.getOut_refund_no());
					logger.error("退款上送银行订单号为："+bankOrder.getOutOrderId());
					logger.error("退款订单号为："+bankOrder.getOrderId());
					if (refundItem.getOut_refund_no().equals(bankOrder.getOutOrderId())) {
						if (WechatScanConstants.WECHAT_WCPAY_REFUND_QUERY_SUCCESS.equals(refundItem.getRefund_status())) {
							// 成功处理
							checkOrderResult.setSuccess(true);
							InAccInfo accInfo = new InAccInfo();
							accInfo.setOrderId(bankOrder.getOrderId());
							accInfo.setAmount(res.getAmount());//退款金额
							accInfo.setRetCode("00");
							accInfo.setCardType(BankCardType.Unknown.toString());
							checkOrderResult.setAccInfo(accInfo);
							logger.error("微信WCPAY支付refund订单：" + bankOrder.getOrderId() + "的交易银行处理成功。"
									 + "返回码：" + refundItem.getRefund_status());
						} else if (WechatScanConstants.WECHAT_WCPAY_REFUND_QUERY_FAIL
								.equals(refundItem.getRefund_status())) {
							// 失败处理
							checkOrderResult.setBankFailure(true);
							InAccInfo accInfo = new InAccInfo();
							accInfo.setOrderId(bankOrder.getOrderId());
							accInfo.setAmount(res.getAmount());
							accInfo.setRetCode("01");
							accInfo.setCardType(BankCardType.Unknown.toString());
							checkOrderResult.setAccInfo(accInfo);
							logger.error("微信WCPAY支付refund订单：" + bankOrder.getOrderId() + "的交易退款失败。"
									+ "返回码：" +refundItem.getRefund_status());
							String errMsg = res.getMessage();
							if (errMsg != null) {
								checkOrderResult.setErrMsg(errMsg);
							} else {
								checkOrderResult.setErrMsg("银行返回退款交易失败。");
							}
						} else if (WechatScanConstants.WECHAT_WCPAY_REFUND_QUERY_PROCESSING.equals(
								refundItem.getRefund_status())) {
							logger.error("微信WCPAY支付refund订单：" + bankOrder.getOrderId() + "的退款交易进行中" + "返回码："
									+ refundItem.getRefund_status());
							String errMsg = res.getMessage();
							if (errMsg != null) {
								checkOrderResult.setErrMsg(errMsg);
							} else {
								checkOrderResult.setErrMsg("银行返回退款交易处理中.");
							}
						} else if (WechatScanConstants.WECHAT_WCPAY_REFUND_QUERY_NOTSURE.equals(
								refundItem.getRefund_status())) {
							if(bankOrder.getOrderStatus().equals(BankOrderStatus.ACCEPTED)){
			        			  //订单为已受理状态时，不允许修改
								logger.error("微信WCPAY支付refund订单：" + bankOrder.getOrderId() + "的退款交易不存在" + "返回码："
										+ refundItem.getRefund_status());
			                    checkOrderResult.setErrMsg("订单为已受理状态，未发往银行，请耐心等待");
			        		}
			        		else{
								logger.error("微信WCPAY支付refund订单：" + bankOrder.getOrderId() + "的退款交易不存在" + "返回码："
										+ refundItem.getRefund_status());
								String errMsg = res.getErrMessage();
								if (errMsg != null) {
									checkOrderResult.setErrMsg(errMsg);
								} else {
									checkOrderResult.setErrMsg("银行返回退款交易不存在。");
								}
								// 查询订单不存在
								checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5041);
			        		}
						} else if (WechatScanConstants.WECHAT_WCPAY_REFUND_QUERY_CHANGE.equals(
								refundItem.getRefund_status())) {
							logger.error("微信WCPAY支付refund订单：" + bankOrder.getOrderId() + "的退款交易转入代发" + "返回码："
									+refundItem.getRefund_status());
							String errMsg = res.getMessage();
							if (errMsg != null) {
								checkOrderResult.setErrMsg(errMsg);
							} else {
								checkOrderResult.setErrMsg("银行返回退款交易转入代发。");
							}
						}
					}

				}
			} else {
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
				if ("Refund not exists".equals(res.getErr_code())) {
					if(bankOrder.getOrderStatus().equals(BankOrderStatus.ACCEPTED)){
						checkOrderResult.setErrMsg("系统返回对账结果为空,订单已受理，请耐心等待");
					}else{
						checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5041);
						checkOrderResult.setErrMsg("系统返回对账结果为空");
					}
				}
				if (res.getErr_code().equals("REFUND_FAIL")&&"已撤销".equals(res.getErr_msg())) {
					checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5041);
					checkOrderResult.setErrMsg("退款已经撤销");
					logger.error("退款订单：" + bankOrder.getOrderId() + "，退款已经撤销,可以手工处理。" + "err_code：" + res.getErr_code() + "。错误信息为："
							+ res.getErr_msg());
				}
				logger.error("退款订单：" + bankOrder.getOrderId() + "，查询失败" + "err_code：" + res.getErr_code() + "。错误信息为："
						+ res.getMessage());	
			}
		}else{
			checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
			checkOrderResult.setErrMsg("微信WCPAY返回验签失败");
			logger.error("微信WCPAY退款订单：" + bankOrder.getOrderId() + "，验签失败" + "status：" + res.getStatus() + "。返回信息为："
					+ res.getMessage());
		}
		return checkOrderResult;
	}
	@Override
	public BankOrder getDbOrder() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BaseMessage dayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result getDayendMsg(String string) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<CheckOrderResult> checkDayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
		// TODO Auto-generated method stub
		return null;
	}

}
